package com.cungmua.app.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.cungmua.app.R;
import com.cungmua.app.adapter.SkuListAdapter;
import com.cungmua.app.base.BaseDrawerActivitys;
import com.cungmua.app.handler.BonusHandler;
import com.cungmua.app.handler.CartInfoHandler;
import com.cungmua.app.handler.CartItemSelectedHandler;
import com.cungmua.app.model.Cart;
import com.cungmua.app.model.CartItem;
import com.cungmua.app.model.DealDetails;
import com.cungmua.app.model.SKU;
import com.cungmua.app.model.request.BonusRequest;
import com.cungmua.app.model.request.CartInfoRequest;
import com.cungmua.app.model.response.BonusResponse;
import com.cungmua.app.model.response.CartInfoResponse;
import com.cungmua.app.task.BonusTask;
import com.cungmua.app.task.CartInfoTask;
import com.cungmua.app.utils.AppUtils;
import com.cungmua.app.view.ExpandableHeightListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kelvin.nguyen on 6/25/14.
 */
public class BuyActivity extends BaseDrawerActivitys implements CartItemSelectedHandler,BonusHandler, View.OnClickListener, CartInfoHandler {
    private LinearLayout layoutSelectSize;
    //    private LinearLayout layoutSizes;
    private LinearLayout layoutSelectColor;
    //    private LinearLayout layoutColors;
    private Spinner spnSize;
    private Spinner spnColor;
    private ExpandableHeightListView listSKU;
    private Button btnBuy;
    private Button btnAddToCart;
    private DealDetails details;
    private SkuListAdapter skuAdapter;
    private List<CartItem> selectedItems;
    private String currentSize = "";
    private String currentColor = "";
    private TextView lblOr;
    private ImageView icon_home;
    private Button icon_cart;
    private LinearLayout btnCart;
    private int moneyBonus=0;

    private TextView txtBonusPoint;
    private TextView txtTotal;
    private TextView txtShipPrice;
    private TextView txtPrice;
    private String priceString = "";
    private boolean isFirst=false;


    private void filter() {
        List<SKU> filteredList = new ArrayList<SKU>();

        for (SKU sku : details.getSkuList()) {
            if (sku.getSizeName().equals(currentSize) && sku.getColorName().equals(currentColor)) {
                filteredList.add(sku);
            }
        }
        skuAdapter.setDataSource(filteredList);
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_buy;
    }

    @Override
    public void updateView() {
        isFirst = false;
        final ArrayAdapter<String> adapterColor = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item);
        adapterColor.addAll(details.getColorList());
        spnColor.setAdapter(adapterColor);
        if (details.getColorList().size() < 1)
            layoutSelectColor.setVisibility(View.GONE);

        final ArrayAdapter<String> adapterSize = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item);
        adapterSize.addAll(details.getSizeList());
        spnSize.setAdapter(adapterSize);
        if (details.getSizeList().size() < 1)
            layoutSelectSize.setVisibility(View.GONE);

        spnSize.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                currentSize = adapterSize.getItem(i).toString();
                filter();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        spnColor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                currentColor = adapterColor.getItem(i).toString();
                filter();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        if (getCurrentUser().getId() == 0){
            login();
            return;
        }


        BonusRequest requests = new BonusRequest(getDeviceId(), getToken());

        requests.setUserId(getCurrentUser().getId());
        BonusTask task = new BonusTask(this, this);
        task.execute(requests);

        skuAdapter.setDataSource(details.getSkuList());

        if (getCurrentCart().getItems().size() > 0) {
            btnBuy.setVisibility(View.GONE);
            lblOr.setVisibility(View.GONE);
            btnAddToCart.setBackgroundResource(R.drawable.btn_gocart_green);
        }

        updatePrice();
    }


    @Override
    public void loadControls(Bundle savedInstanceState) {
        details = (DealDetails) getIntent().getExtras().getSerializable(IK_DEAL_DETAILS);



        selectedItems = new ArrayList<CartItem>();

        layoutSelectSize = (LinearLayout) findViewById(R.id.layoutSelectSize);
        layoutSelectColor = (LinearLayout) findViewById(R.id.layoutSelectColor);

        listSKU = (ExpandableHeightListView) findViewById(R.id.listSKU);
        skuAdapter = new SkuListAdapter(details.getId(), this, details, this, selectedItems);

        spnColor = (Spinner) findViewById(R.id.spnColor);
        spnSize = (Spinner) findViewById(R.id.spnSize);

        txtBonusPoint = (TextView) findViewById(R.id.txtBonusPoint);
        txtTotal = (TextView) findViewById(R.id.txtTotal);
        txtShipPrice = (TextView) findViewById(R.id.txtShipPrice);
        txtPrice = (TextView) findViewById(R.id.txtPrice);


        listSKU.setExpanded(true);
        listSKU.setAdapter(skuAdapter);

        btnBuy = (Button) findViewById(R.id.btnBuy);
        lblOr = (TextView) findViewById(R.id.lbl_or);
        btnBuy.setOnClickListener(this);
        btnAddToCart = (Button) findViewById(R.id.btnAddToCart);
        btnAddToCart.setOnClickListener(this);

        icon_home=(ImageView)findViewById(R.id.icon_home);
        icon_cart=(Button)findViewById(R.id.icon_cart);
        btnCart=(LinearLayout)findViewById(R.id.btnCart);


        Cart currentCart=getCurrentCart();
        icon_cart.setText(currentCart.getTotalQuantity()+"");

        icon_home.setOnClickListener(new ImageView.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMenu();
            }
        });

        btnCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToYourCart();
            }
        });

    }

    @Override
    public void onCartItemSelected(CartItem selectedItem) {

        CartItem currentItem = null;

        for (CartItem item : selectedItems) {
            if (item.getProductId() == selectedItem.getProductId() && item.getSkuId() == selectedItem.getSkuId()) {
                currentItem=item;
            }
        }

        if (currentItem == null) {
            if (selectedItem.getQuantity() > 0)
                selectedItems.add(selectedItem);
        } else {
            currentItem.setQuantity(selectedItem.getQuantity());
            if (selectedItem.getQuantity() == 0)
                selectedItems.remove(currentItem);
        }

        if (selectedItems.size() > 0) {
            btnAddToCart.setEnabled(true);
            btnBuy.setEnabled(true);
        }

        int price=0;
        for (CartItem item:selectedItems){
            price=price+item.getPrice()*item.getQuantity();
        }



        if(getCurrentCity().getId()==-1 && price < 500000){
            priceString = getString(R.string.full_price_string,
                    AppUtils.getFullPriceString(price+KEY_DEFAULT_FEE-moneyBonus));
            txtTotal.setText(priceString);
        }else{
            priceString = getString(R.string.full_price_string,
                    AppUtils.getFullPriceString(price-moneyBonus));
            txtTotal.setText(priceString);
            txtShipPrice.setText("Miễn phí");

        }

        txtPrice.setText(getString(R.string.full_price_string,
                AppUtils.getFullPriceString(price)));


    }


    @Override
    public void deleteSelectedItems(CartItem item) {

    }

    @Override
    public void onBackDealDetails(int id) {

    }

    @Override
    public void onClick(View view) {
        if (view == btnAddToCart) {
            if (selectedItems.size() > 0) {
                List<CartItem> inCartItems = getCurrentCart().itemsByGroup(details.getId());

                for (CartItem cartItem : inCartItems) {
                    for (CartItem selectedItem : selectedItems) {
                        if (cartItem.getProductId() == selectedItem.getProductId() &&
                                cartItem.getSkuId() == selectedItem.getSkuId()) {
                            selectedItem.setQuantity(selectedItem.getQuantity() + cartItem.getQuantity());
                        }
                    }
                }

                Cart currentCart = getCurrentCart();
                currentCart.getItems().removeAll(currentCart.itemsByGroup(details.getId()));
                currentCart.getItems().addAll(selectedItems);

                setCurrentCart(currentCart);

                goToYourCart();
            } else {
                AlertDialog dialog = new AlertDialog.Builder(this)
                        .setMessage(R.string.please_enter_quantity)
                        .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        })
                        .show();
            }
        } else if (view == btnBuy) {
            if (selectedItems.size() > 0) {
                Cart currentCart = getCurrentCart();
                currentCart.getItems().removeAll(currentCart.itemsByGroup(details.getId()));
                currentCart.getItems().addAll(selectedItems);

                setCurrentCart(currentCart);

                CartInfoRequest request = new CartInfoRequest(getDeviceId(), getToken());
                request.setUserId(getCurrentUser().getId());
                request.setCityId(getCurrentCity().getId());
                request.setProductList(currentCart.toString());
                CartInfoTask task = new CartInfoTask(this, this);
                if (!currentCart.toString().isEmpty())
                    task.execute(request);
            } else {
                AlertDialog dialog = new AlertDialog.Builder(this)
                        .setMessage(R.string.please_enter_quantity)
                        .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        })
                        .show();
            }
        }

    }

    @Override
    public void onCartInfoReceived(CartInfoResponse response) {

        if(response.getCode()==0) {
            txtShipPrice.setText(response.getData().getShippingFee() + "");

            if (isFirst) {
                String totalPrice = String.valueOf(response.getData().getTotalPrice());
                goToMakeOrder(totalPrice);
            }
        }
        isFirst=true;
    }


    public void resetPriceFields() {
        txtBonusPoint.setText("--");
        txtShipPrice.setText(getString(R.string.free));

        String priceString = getString(R.string.full_price_string,
                AppUtils.getFullPriceString(0));
        txtTotal.setText(priceString);
        btnBuy.setVisibility(View.INVISIBLE);
        txtPrice.setText(priceString);


    }

    public void updatePrice() {
        Cart currentCart = getCurrentCart();
        CartInfoRequest request = new CartInfoRequest(getDeviceId(), getToken());
        request.setUserId(getCurrentUser().getId());
        request.setCityId(getCurrentCity().getId());
        request.setProductList(currentCart.toString());

        CartInfoTask task = new CartInfoTask(this, this);

        if (!currentCart.toString().isEmpty()) {
            task.execute(request);
            icon_cart.setVisibility(View.VISIBLE);
        }else {
           // cartEmpty.setVisibility(View.VISIBLE);
            icon_cart.setVisibility(View.GONE);
            //resetPriceFields();
        }
    }

    @Override
    public void onBonus(BonusResponse response) {
        //txtBonusPoint.setText(response.getData().getMoneyReceived());
        if (String.valueOf(response.getData().getMoneyReceived()).contains("0")){
            txtBonusPoint.setText("-" + AppUtils.getFullPriceString(response.getData().getMoneyRemain()) + "đ");
        } else {
            moneyBonus=response.getData().getMoneyRemain();
            txtBonusPoint.setText(response.getData().getMoneyRemain()+"");
        }
    }
}
